<template>
    <el-card style="margin-bottom: 10px;width: 90%;">
        <div style="display: flex;justify-content: space-between;align-items: center;">
            <h1 style="margin: 0;font-size: 24px;">SeedMsg|通用的消息推送服务</h1>
            <span style="font-size: 14px;">服务状态：<span :style="`color: ${status ? 'green' : 'red'};`">{{ status ?
                '已连接' : '未连接'
                    }}</span></span>
        </div>
    </el-card>
    <el-card style="margin-bottom: 10px;width: 90%;">
        <div style="margin: 10px 0;display: flex;justify-content: right;">
            <el-button type="primary" @click="useRouter().push('/crontime')" :disabled="!status">任务时间</el-button>
            <el-button type="primary" @click="useRouter().push('/variable')" :disabled="!status">变量表</el-button>
            <el-button type="primary" @click="addDialogVisible = true" :disabled="!status">新增</el-button>
        </div>
        <div>
            <el-table :data="task_list" style="width: 100%" border stripe>
                <el-table-column prop="id" label="Id" width="100" align="center" />
                <el-table-column prop="name" label="任务名称" width="180" align="center" />
                <el-table-column prop="cron" label="Cron" width="180" align="center">
                    <template #default="scope">
                        <div>
                            <span>{{crontime_options.find(v => v.value === scope.row.cron)?.label}}</span>
                            <!-- <span>{{ scope.row.cron }}</span> -->
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="webhook" label="Webhook" align="center" />
                <!-- <el-table-column prop="secret" label="Secret" width="240" align="center" /> -->
                <el-table-column prop="template_id" width="150" align="center">
                    <template #header>
                        <el-tooltip content="点击查看飞书卡片编辑器" placement="top">
                            <span>Template_id<el-link style="font-size: 10px;" underline="never"
                                    href="https://open.feishu.cn/cardkit" target="_blank">卡片编辑器</el-link></span>
                        </el-tooltip>


                    </template>
                    <template #default="scope">
                        <el-link underline="never"
                            :href="`https://open.feishu.cn/cardkit/editor?cardId=${scope.row.template_id}`"
                            target="_blank">
                            {{ scope.row.template_id }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="template_variables" label="变量表" width="300" align="center">
                    <template #default="scope">
                        <div style="display: flex;flex-wrap: wrap;gap: 5px;">
                            <el-tag v-for="item in scope.row.template_variables" :key="item" type="primary"
                                effect="plain" style="margin-right: 5px;">{{template_variables_options.find(v =>
                                    v.value
                                    ===
                                    item)?.label}}</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="180" align="center">
                    <template #default="scope">
                        <el-switch :disabled="!status" @change="onSwitchChange(scope.row)" v-model="scope.row.status"
                            :active-value="1" :inactive-value="0" active-text="开启" inactive-text="关闭" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="140" align="center">
                    <template #default="scope">
                        <div style="margin-bottom: 5px;">
                            <el-button style="width: 100%;" size="small" color="#4e8e2f"
                                @click="viewNextDatesHandle(scope.row)" :disabled="!status">查看执行表</el-button>
                        </div>
                        <div class="btn" style="display: flex;gap:5px;">
                            <el-button style="width: 100%;" size="small" color="#a77730"
                                @click="updateTaskHandle(scope.row)" :disabled="!status">编辑</el-button>
                            <el-button style="width: 100%;" size="small" color="#b25252"
                                @click="deleteTaskHandle(scope.row)" :disabled="!status">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </el-card>
    <el-dialog v-model="addDialogVisible" draggable title="新增任务" :before-close="addDialogClose">
        <div>
            <el-form :model="task_form" :rules="task_form_rules" label-width="auto" ref="add_task_form_ref">
                <el-form-item label="任务名称" prop="name">
                    <el-input v-model="task_form.name" />
                </el-form-item>
                <el-form-item label="Cron" prop="cron">
                    <el-select v-model="task_form.cron" placeholder="选择Cron预设" clearable style="width: 240px">
                        <el-option v-for="item in crontime_options" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="Webhook" prop="webhook">
                    <el-input v-model="task_form.webhook" />
                </el-form-item>
                <el-form-item label="Secret" prop="secret">
                    <el-input v-model="task_form.secret" />
                </el-form-item>
                <el-form-item label="Template_id" prop="template_id">
                    <el-input v-model="task_form.template_id" />
                </el-form-item>
                <el-form-item label="变量" prop="template_variables">
                    <el-select v-model="task_form.template_variables" clearable multiple placeholder="选择预设变量"
                        style="width: 240px">
                        <el-option v-for="item in template_variables_options" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div>
                <el-button @click="addDialogClose">取消</el-button>
                <el-button type="primary" @click="addTaskHandle">添加</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="deleteDialogVisible" draggable title="删除任务" :before-close="deleteDialogClose">
        <div>
            是否删除任务：{{ delete_task_form.name }}
        </div>
        <template #footer>
            <div>
                <el-button @click="deleteDialogClose">取消</el-button>
                <el-button type="danger" @click="deleteTask">删除</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog width="400" v-model="nextDatesDialogVisible" draggable title="执行表" :before-close="nextDatesDialogClose">
        <div style="display: flex;gap:5px">
            <el-button size="small" type="primary" @click="viewNextDates">获取</el-button>
            <span>后续<el-input size="small" style="width: 50px;" v-model="nextDatesForm.count"
                    placeholder="数量" />条执行计划时间,</span>
            <el-button size="small" type="warning" @click="runTask">立即执行</el-button>
        </div>
        <div style="display: flex;flex-direction: column;align-items: center;margin: 10px 0;gap: 5px;">
            <el-tag type="primary" v-for="item in nextDates" :key="item" style="width: fit-content;">
                {{ item }}
            </el-tag>
        </div>
    </el-dialog>
    <el-dialog v-model="updateDialogVisible" draggable title="更新任务" :before-close="updateDialogClose">
        <div>
            <el-form :model="update_task_form" :rules="task_form_rules" label-width="auto" ref="update_task_form_ref">
                <el-form-item label="任务名称" prop="name">
                    <el-input v-model="update_task_form.name" />
                </el-form-item>
                <el-form-item label="Cron" prop="cron">
                    <el-select v-model="update_task_form.cron" placeholder="选择Cron预设" clearable style="width: 240px">
                        <el-option v-for="item in crontime_options" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="Webhook" prop="webhook">
                    <el-input disabled v-model="update_task_form.webhook" />
                </el-form-item>
                <el-form-item label="Secret" prop="secret">
                    <el-input disabled v-model="update_task_form.secret" />
                </el-form-item>
                <el-form-item label="Template_id" prop="template_id">
                    <el-input v-model="update_task_form.template_id" />
                </el-form-item>
                <el-form-item label="变量" prop="template_variables">
                    <el-select v-model="update_task_form.template_variables" clearable multiple placeholder="选择预设变量"
                        style="width: 240px">
                        <el-option v-for="item in template_variables_options" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div>
                <el-button @click="updateDialogClose">取消</el-button>
                <el-button type="primary" @click="updateTask">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
const { connect, disconnect, status, emit, on, off } = useSocket()

// 初始化连接
onMounted(() => {
    connect()
    setupEventListeners()
})

// 清理事件监听
onUnmounted(() => {
    off('getTaskList')
    off('addTask')
    off('deleteTask')
    off('changeTaskStatus')
    off('viewNextDates')
    off('runTask')
    disconnect()
})

const setupEventListeners = () => {
    emit('getTaskList')
    emit('getVariableList')
    emit('getCronTimeList')
    on('getTaskList', (list) => task_list.value = list)
    on('getVariableList', handleGetVariableList)
    on('getCronTimeList', handleGetCronTimeList)
    on('addTask', handleAddTask)
    on('deleteTask', handleDeleteTask)
    on('changeTaskStatus', handleStatusChange)
    on('viewNextDates', handleViewDates)
    on('runTask', handleRunTask)
}

const handleAddTask = (data: any) => {
    ElMessage({ message: data.message, type: data.type, showClose: true })
    emit('getTaskList')
}

const handleDeleteTask = (data: any) => {
    ElMessage({ message: data.message, type: data.type, showClose: true })
    emit('getTaskList')
}

const handleStatusChange = (data: any) => {
    ElMessage({ message: data.message, type: data.type, showClose: true })
    emit('getTaskList')
}

const handleViewDates = (data: any) => {
    nextDates.value = data.nextDates
}

const handleRunTask = (data: any) => {
    ElMessage({ message: data.message, type: data.type, showClose: true })
    emit('getTaskList')
}

const handleGetVariableList = (list: any) => {
    template_variables_options.value = list.map((item: any) => {
        return {
            value: item.content,
            label: item.name,
        }
    })
}

const handleGetCronTimeList = (list: any) => {
    crontime_options.value = list.map((item: any) => {
        return {
            value: item.cron,
            label: item.name,
        }
    })
}

const task_list = ref<any[]>([])

const crontime_options = ref<any[]>([])

const add_task_form_ref = ref()

const template_variables_options = ref<any[]>([])

const task_form = ref({
    name: '',
    cron: '',
    webhook: '',
    secret: '',
    template_id: '',
    template_variables: [],
    status: 1
})

const task_form_rules = ref({
    name: [{ required: true, message: '请输入任务名称', trigger: 'blur' },],
    cron: [{ required: true, message: '请选择Cron预设', trigger: 'change' },],
    webhook: [{ required: true, message: '请输入Webhook地址', trigger: 'blur' },],
    secret: [{ required: true, message: '请输入Secret', trigger: 'blur' },],
    template_id: [{ required: true, message: '请输入Template id', trigger: 'blur' },],
    template_variables: [{ required: false, message: '请选择变量预设', trigger: 'change' },],
})

const addDialogVisible = ref(false)

const addDialogClose = () => {
    addDialogVisible.value = false
    add_task_form_ref.value.resetFields()
}

const addTaskHandle = () => {
    add_task_form_ref.value.validate((valid: boolean) => {
        if (valid) {
            emit('addTask', task_form.value)
            addDialogClose()
        }
    })
}

const deleteDialogVisible = ref(false)

const delete_task_form = ref({
    id: '',
    name: '',
})

const deleteDialogClose = () => {
    deleteDialogVisible.value = false
}

const deleteTaskHandle = (row: any) => {
    delete_task_form.value.id = row.id
    delete_task_form.value.name = row.name
    deleteDialogVisible.value = true
}

const deleteTask = () => {
    emit('deleteTask', delete_task_form.value)
    deleteDialogClose()
}

const onSwitchChange = (row: any) => {
    const data = {
        id: row.id,
        name: row.name,
        status: row.status
    }
    emit('changeTaskStatus', data)
}

const nextDatesForm = ref({
    id: '',
    name: '',
    count: 5,
})
const nextDates = ref([])
const nextDatesDialogVisible = ref(false)

const nextDatesDialogClose = () => {
    nextDatesDialogVisible.value = false
    nextDates.value = []
}

const viewNextDatesHandle = (row: any) => {
    nextDatesForm.value.id = row.id
    nextDatesForm.value.name = row.name
    nextDatesDialogVisible.value = true
}

const viewNextDates = () => {
    emit('viewNextDates', nextDatesForm.value)
}

const runTask = () => {
    emit('runTask', nextDatesForm.value)
}

const update_task_form_ref = ref()

const update_task_form = ref({
    id: '',
    name: '',
    cron: '',
    webhook: '',
    secret: '',
    template_id: '',
    template_variables: [],
    status: ''
})

const updateDialogVisible = ref(false)

const updateDialogClose = () => {
    updateDialogVisible.value = false
}

const updateTaskHandle = (row: any) => {
    update_task_form.value.id = row.id
    update_task_form.value.name = row.name
    update_task_form.value.cron = row.cron
    update_task_form.value.webhook = row.webhook
    update_task_form.value.secret = row.secret
    update_task_form.value.template_id = row.template_id
    update_task_form.value.template_variables = row.template_variables
    update_task_form.value.status = row.status
    updateDialogVisible.value = true
}

const updateTask = async () => {
    update_task_form_ref.value.validate((valid: boolean) => {
        if (valid) {
            emit('updateTask', update_task_form.value)
            updateDialogClose()
        }
    })
}
</script>

<style>
.btn .el-button+.el-button {
    margin-left: 0;
}
</style>